<template>
  <div class="main-app-data-demo">
    <div class="page-header">
      <h1>子应用1 - 主应用数据交互案例</h1>
      <el-tag type="success" size="large">{{ appInfo.appType.toUpperCase() }}</el-tag>
    </div>

    <!-- 环境信息 -->
    <el-card class="demo-card" header="环境信息">
      <div class="info-grid">
        <div class="info-item">
          <strong>应用名称:</strong>
          <span>{{ appInfo.subAppName || '子应用1' }}</span>
        </div>
        <div class="info-item">
          <strong>运行模式:</strong>
          <el-tag :type="appInfo.isSubApp ? 'success' : 'warning'">
            {{ appInfo.isSubApp ? '微前端模式' : '独立模式' }}
          </el-tag>
        </div>
        <div class="info-item">
          <strong>路由模式:</strong>
          <span>{{ appInfo.routerMode }}</span>
        </div>
        <div class="info-item">
          <strong>主应用连接:</strong>
          <el-tag :type="hasMainAppConnection ? 'success' : 'danger'">
            {{ hasMainAppConnection ? '已连接' : '未连接' }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 接收到的主应用 Props -->
    <el-card class="demo-card" header="主应用传递的 Props" v-if="mainAppProps">
      <div class="props-display">
        <h4>Props 结构:</h4>
        <pre>{{ JSON.stringify(propsStructure, null, 2) }}</pre>
      </div>
      
      <div class="props-actions" v-if="mainAppProps.mainAppData">
        <h4>可用的主应用方法:</h4>
        <div class="action-buttons">
          <el-button type="primary" @click="testSetUser">测试设置用户</el-button>
          <el-button type="success" @click="testSetTheme">测试切换主题</el-button>
          <el-button type="info" @click="testSendNotification">发送通知给主应用</el-button>
          <el-button type="warning" @click="testUpdateSharedData">更新共享数据</el-button>
        </div>
      </div>
    </el-card>

    <!-- 全局状态监听 -->
    <el-card class="demo-card" header="全局状态监听">
      <div class="state-monitor">
        <div class="current-state">
          <h4>当前全局状态:</h4>
          <pre v-if="globalState">{{ JSON.stringify(globalState, null, 2) }}</pre>
          <el-empty v-else description="暂无全局状态数据" />
        </div>
        
        <div class="state-changes" v-if="stateChanges.length > 0">
          <h4>状态变化历史 (最近10条):</h4>
          <div class="change-list">
            <div 
              v-for="(change, index) in stateChanges.slice(-10)" 
              :key="index"
              class="change-item"
            >
              <div class="change-time">{{ change.timestamp }}</div>
              <div class="change-content">
                <strong>变化:</strong> {{ change.description }}
              </div>
              <div class="change-data" v-if="change.data">
                <pre>{{ JSON.stringify(change.data, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 子应用向主应用发送数据 -->
    <el-card class="demo-card" header="向主应用发送数据">
      <div class="send-data-section">
        <div class="form-section">
          <h4>发送用户信息:</h4>
          <el-form :model="userForm" label-width="100px">
            <el-form-item label="用户名:">
              <el-input v-model="userForm.name" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="角色:">
              <el-select v-model="userForm.role" placeholder="请选择角色">
                <el-option label="管理员" value="admin" />
                <el-option label="用户" value="user" />
                <el-option label="访客" value="guest" />
              </el-select>
            </el-form-item>
            <el-form-item label="部门:">
              <el-input v-model="userForm.department" placeholder="请输入部门" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sendUserToMain">发送用户信息</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="form-section">
          <h4>发送通知:</h4>
          <el-form :model="notificationForm" label-width="100px">
            <el-form-item label="标题:">
              <el-input v-model="notificationForm.title" placeholder="通知标题" />
            </el-form-item>
            <el-form-item label="内容:">
              <el-input 
                v-model="notificationForm.message" 
                type="textarea" 
                :rows="3"
                placeholder="通知内容" 
              />
            </el-form-item>
            <el-form-item label="类型:">
              <el-select v-model="notificationForm.type" placeholder="通知类型">
                <el-option label="信息" value="info" />
                <el-option label="成功" value="success" />
                <el-option label="警告" value="warning" />
                <el-option label="错误" value="error" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="sendNotificationToMain">发送通知>></el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 主应用工具函数测试 -->
    <el-card class="demo-card" header="主应用工具函数" v-if="mainAppProps?.utils">
      <div class="utils-section">
        <h4>测试主应用提供的工具函数:</h4>
        <div class="action-buttons">
          <el-button @click="testShowMessage('info')">显示信息消息</el-button>
          <el-button @click="testShowMessage('success')">显示成功消息</el-button>
          <el-button @click="testShowMessage('warning')">显示警告消息</el-button>
          <el-button @click="testShowMessage('error')">显示错误消息</el-button>
          <el-button @click="testShowConfirm">显示确认对话框</el-button>
        </div>
      </div>
    </el-card>

    <!-- 路由跳转测试 -->
    <el-card class="demo-card" header="路由跳转">
      <div class="navigation-section">
        <h4>跳转到主应用或其他子应用:</h4>
        <div class="action-buttons">
          <el-button type="primary" @click="navigateToMain('/')">回到主应用首页</el-button>
          <el-button type="success" @click="navigateToSubApp2">跳转到子应用2</el-button>
          <el-button type="info" @click="navigateInCurrentApp('/about')">子应用内跳转</el-button>
        </div>
      </div>
    </el-card>

    <!-- 调试信息 -->
    <el-card class="demo-card" header="调试信息" v-if="isDev">
      <div class="debug-section">
        <h4>完整的 Props 数据:</h4>
        <pre>{{ JSON.stringify(mainAppProps, null, 2) }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useQiankun } from '@/utils/qiankun'

const router = useRouter()

// 使用 qiankun 工具函数
const appInfo = useQiankun()

// 响应式数据
const globalState = ref(null)
const stateChanges = ref([])
const isDev = import.meta.env.DEV

// 表单数据
const userForm = ref({
  name: '子应用1用户',
  role: 'user',
  department: '前端开发部'
})

const notificationForm = ref({
  title: '来自子应用1的通知',
  message: '这是一条测试通知消息',
  type: 'info'
})

// 计算属性
const mainAppProps = computed(() => appInfo.props)
const hasMainAppConnection = computed(() => !!mainAppProps.value)

const propsStructure = computed(() => {
  if (!mainAppProps.value) return {}
  
  return {
    routerBase: mainAppProps.value.routerBase,
    hasActions: !!mainAppProps.value.actions,
    hasMainAppData: !!mainAppProps.value.mainAppData,
    hasUtils: !!mainAppProps.value.utils,
    mainAppInfo: mainAppProps.value.mainAppInfo,
    availableMethods: mainAppProps.value.mainAppData ? 
      Object.getOwnPropertyNames(mainAppProps.value.mainAppData).filter(name => 
        typeof mainAppProps.value.mainAppData[name] === 'function'
      ) : []
  }
})

// 状态变化监听
let stateChangeListener = null

// 方法
const updateGlobalState = () => {
  if (appInfo.subAppData) {
    globalState.value = appInfo.subAppData.getGlobalState()
  }
}

const addStateChange = (description, data = null) => {
  stateChanges.value.push({
    timestamp: new Date().toLocaleString(),
    description,
    data
  })
}

// 测试方法
const testSetUser = () => {
  if (appInfo.subAppData) {
    appInfo.subAppData.updateUser({
      id: Date.now(),
      name: '子应用1测试用户',
      role: 'tester',
      from: '子应用1'
    })
    ElMessage.success('用户信息已发送到主应用')
    addStateChange('发送用户信息到主应用', { from: '子应用1' })
  }
}

const testSetTheme = () => {
  if (appInfo.subAppData) {
    const themes = ['light', 'dark', 'blue', 'green']
    const currentTheme = globalState.value?.theme || 'light'
    const newTheme = themes[(themes.indexOf(currentTheme) + 1) % themes.length]
    
    appInfo.subAppData.switchTheme(newTheme)
    ElMessage.success(`主题已切换为: ${newTheme}`)
    addStateChange('切换主题', { theme: newTheme })
  }
}

const testSendNotification = () => {
  if (appInfo.subAppData) {
    appInfo.subAppData.sendNotification({
      title: '来自子应用1的测试通知',
      message: '这是一条自动生成的测试通知',
      type: 'info'
    })
    ElMessage.success('通知已发送')
    addStateChange('发送测试通知')
  }
}

const testUpdateSharedData = () => {
  if (appInfo.subAppData) {
    appInfo.subAppData.updateSharedData({
      lastAction: '子应用1数据更新',
      timestamp: new Date().toISOString(),
      counter: (globalState.value?.sharedData?.counter || 0) + 1
    })
    ElMessage.success('共享数据已更新')
    addStateChange('更新共享数据')
  }
}

// 表单提交方法
const sendUserToMain = () => {
  if (appInfo.subAppData) {
    appInfo.subAppData.updateUser({
      ...userForm.value,
      id: Date.now(),
      from: '子应用1',
      timestamp: new Date().toISOString()
    })
    ElMessage.success('用户信息已发送到主应用')
    addStateChange('发送自定义用户信息', userForm.value)
  } else {
    ElMessage.warning('未连接到主应用')
  }
}

const sendNotificationToMain = () => {
  if (appInfo.subAppData) {
    appInfo.subAppData.sendNotification({
      ...notificationForm.value,
      from: '子应用1',
      timestamp: new Date().toISOString()
    })
    ElMessage.success('通知已发送到主应用')
    addStateChange('发送自定义通知', notificationForm.value)
  } else {
    ElMessage.warning('未连接到主应用')
  }
}

// 工具函数测试
const testShowMessage = (type) => {
  const messages = {
    info: '这是一条信息消息',
    success: '操作成功！',
    warning: '这是一条警告消息',
    error: '发生了错误！'
  }
  
  if (appInfo.subAppData) {
    appInfo.subAppData.showMessage(messages[type], type)
  } else {
    ElMessage[type](messages[type])
  }
}

const testShowConfirm = async () => {
  try {
    if (appInfo.subAppData) {
      const result = await appInfo.subAppData.showConfirm('确认要执行这个操作吗？')
      ElMessage.success(result ? '用户确认了操作' : '用户取消了操作')
    } else {
      const result = await ElMessageBox.confirm('确认要执行这个操作吗？', '提示')
      ElMessage.success('用户确认了操作')
    }
  } catch (error) {
    ElMessage.info('用户取消了操作')
  }
}

// 导航方法
const navigateToMain = (path) => {
  if (appInfo.subAppData) {
    appInfo.subAppData.navigateToMain(path)
  } else {
    ElMessage.warning('未连接到主应用，无法跳转')
  }
}

const navigateToSubApp2 = () => {
  if (mainAppProps.value?.setMainAppRoute) {
    mainAppProps.value.setMainAppRoute('/sub-app2')
  } else {
    ElMessage.warning('无法跳转到其他子应用')
  }
}

const navigateInCurrentApp = (path) => {
  router.push(path)
}

// 生命周期
onMounted(() => {
  console.log('[子应用1] 组件挂载，qiankun 信息:', appInfo)
  
  // 更新全局状态
  updateGlobalState()
  
  // 设置状态变化监听
  if (typeof window !== 'undefined') {
    // 监听主应用状态变化事件
    const handleUserChanged = (event) => {
      console.log('[子应用1] 用户信息变化:', event.detail)
      addStateChange('用户信息变化', event.detail)
      updateGlobalState()
    }
    
    const handleThemeChanged = (event) => {
      console.log('[子应用1] 主题变化:', event.detail)
      addStateChange('主题变化', { theme: event.detail })
      updateGlobalState()
    }
    
    const handleNotificationReceived = (event) => {
      console.log('[子应用1] 收到通知:', event.detail)
      addStateChange('收到新通知', event.detail)
      updateGlobalState()
    }
    
    window.addEventListener('userChanged', handleUserChanged)
    window.addEventListener('themeChanged', handleThemeChanged)
    window.addEventListener('notificationReceived', handleNotificationReceived)
    
    // 保存监听器引用以便清理
    stateChangeListener = () => {
      window.removeEventListener('userChanged', handleUserChanged)
      window.removeEventListener('themeChanged', handleThemeChanged)
      window.removeEventListener('notificationReceived', handleNotificationReceived)
    }
  }
  
  // 添加初始状态记录
  addStateChange('子应用1组件初始化')
})

onUnmounted(() => {
  // 清理事件监听器
  if (stateChangeListener) {
    stateChangeListener()
  }
})
</script>

<style scoped>
.main-app-data-demo {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e4e7ed;
}

.demo-card {
  margin-bottom: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.info-item {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.info-item strong {
  color: #303133;
  margin-right: 8px;
}

.props-display, .state-monitor, .debug-section {
  margin-bottom: 20px;
}

.props-display h4, .state-monitor h4, .debug-section h4 {
  margin-bottom: 10px;
  color: #303133;
}

.props-display pre, .debug-section pre {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  line-height: 1.4;
}

.action-buttons {
  margin: 15px 0;
}

.action-buttons .el-button {
  margin: 5px;
}

.current-state pre {
  background: #f0f9ff;
  border: 1px solid #bfdbfe;
  padding: 15px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.change-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.change-item {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.change-item:last-child {
  border-bottom: none;
}

.change-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.change-content {
  margin-bottom: 8px;
}

.change-data pre {
  background: #fafafa;
  padding: 8px;
  border-radius: 4px;
  font-size: 11px;
  margin: 0;
}

.send-data-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 30px;
}

.form-section {
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
}

.form-section h4 {
  margin-bottom: 15px;
  color: #303133;
}

.utils-section, .navigation-section {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.utils-section h4, .navigation-section h4 {
  margin-bottom: 15px;
  color: #303133;
}
</style> 